<template>
  <v-app>
    <!-- 应用栏 -->
    <v-app-bar
      app
      color="primary"
      density="compact"
      dark
    >
      <v-app-bar-title>检测记录</v-app-bar-title>
    </v-app-bar>

    <!-- 主内容区域 -->
    <v-main>
      <v-container class="px-5">
        <v-row v-if="loading">
          <v-progress-linear
            :indeterminate="loading"
            color="purple"
          ></v-progress-linear>
        </v-row>
        <v-row>
          <v-col
            md="4"
            sm="1"
            class="pa-0"
            v-for="item in diagItems"
            :key="item.id"
          >
            <DiagCard :item="item"/>
          </v-col>
        </v-row>
        <v-row class="mt-8 justify-center">
          <v-pagination
            v-model="page"
            v-if="total !== null"
            :length="total"
            density="compact"
            total-visible="5"
            @update:model-value="updatePage"
          ></v-pagination>
        </v-row>
      </v-container>
    </v-main>
  </v-app>
</template>

<script setup>
  import { ref } from "vue";
  import DiagCard from "../components/DiagCard.vue";
  import { getDiagList } from "../api";
  const loading = ref(false);
  const page = ref(1);
  const total = ref(null);

  const diagItems = reactive([]);

  const updatePage = async (newPage) => {
    loading.value = true;
    const param = {
      page: newPage,
    };
    try {
      const response = await getDiagList(param)
      total.value = response.num_pages
      diagItems.splice(0, diagItems.length)
      diagItems.push(...response.records)
    } catch(error) {
      console.error("获取数据失败", error);
      loading.value = false;
      if (error.response && error.response.data.message) {
        errorMessage.value = error.response.data.message;
      } else {
        errorMessage.value = "获取数据异常";
      }
    }
  }

  onMounted(async () => {
    loading.value = true;
    const param = {
      page: 1,
    };
    try {
      const response = await getDiagList(param);
      diagItems.push(...response.records);
      total.value = response.num_pages
      setInterval(() => {
        loading.value = false;
      }, 1000);
    } catch (error) {
      console.error("获取数据失败", error);
      loading.value = false;
      if (error.response && error.response.data.message) {
        errorMessage.value = error.response.data.message;
      } else {
        errorMessage.value = "获取数据异常";
      }
    }
  });
</script>
